package middleware

import (
	"encoding/json"
	"net/http"

	"github.com/sirupsen/logrus"
)

func RecoveryMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if recoveredErr := recover(); recoveredErr != nil {
				logrus.Errorf("Recovered from panic: %v", recoveredErr)
				w.WriteHeader(http.StatusInternalServerError)
				encodeErr := json.NewEncoder(w).Encode(map[string]string{
					"error": "Internal server error",
				})
				if encodeErr != nil {
					return
				}
			}
		}()
		next.ServeHTTP(w, r)
	})
}
